<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/index.js'
import { userUpdateAvatarService } from '@/api/user.js'
import defaultAvatar from '@/assets/default.png'

const userStore = useUserStore()
const imgUrl = ref(userStore.user.user_pic)
const uploadRef = ref()

const onUploadFile = (uploadFile) => {
  // 基于FileReader读取图片
  const reader = new FileReader()
  reader.readAsDataURL(uploadFile.raw)
  reader.onload = () => {
    imgUrl.value = reader.result
  }
}

const submitUpload = async () => {
  await userUpdateAvatarService(imgUrl.value)
  await userStore.getUser()
  ElMessage.success('修改成功！')
}
</script>
<template>
  <PageContainer title="更换头像">
    <el-upload
      ref="uploadRef"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="onUploadFile"
      class="avatar-uploader"
    >
      <img :src="imgUrl || defaultAvatar" class="avatar" />
    </el-upload>
    <el-button
      @click="uploadRef.$el.querySelector('input').click()"
      type="primary"
      >选择头像</el-button
    >
    <el-button class="ml-3" type="success" @click="submitUpload">
      上传
    </el-button>
  </PageContainer>
</template>
<style scoped>
.avatar,
.avatar-uploader {
  border: 1px dashed #8c939d;
  border-radius: 6px;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: block;
}
</style>
